using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace SimpleFramework 
{

    public static class UnityUIImage_Extension
    {
        private static Dictionary<int, long> s_Binder = new Dictionary<int, long>();

        public static void SetSprite(this Image comp, string assetPath, bool useNativeSize = false)
        {
            long uuid;
            int instanceID = comp.GetInstanceID();
            if (s_Binder.TryGetValue(instanceID, out uuid))
            {
                Res.Stop(uuid);
                s_Binder.Remove(instanceID);
            }

            s_Binder[instanceID] = Res.Spawn(assetPath, (IResObjectPool pool, object userData) =>
            {
                Debug.Log("SetSprite:" + pool.Key);
                var sprite = pool.Spawn<Sprite>();
                s_Binder.Remove(instanceID);
                Res.UnSpawn(comp.sprite);
                comp.sprite = sprite;
                if (useNativeSize)
                    comp.SetNativeSize();
            }, null);
        }

        public static void SetSprite(this Image comp, string assetPath, System.Action<Image> onComplete)
        {
            long uuid;
            int instanceID = comp.GetInstanceID();
            if (s_Binder.TryGetValue(instanceID, out uuid))
            {
                Res.Stop(uuid);
                s_Binder.Remove(instanceID);
            }

            s_Binder[instanceID] = Res.Spawn(assetPath, (IResObjectPool pool, object userData) =>
            {
                var sprite = pool.Spawn<Sprite>();
                s_Binder.Remove(instanceID);
                Res.UnSpawn(comp.sprite);
                comp.sprite = sprite;
                onComplete.Invoke(comp);
            }, null);
        }

        public static void ClearSprite(this Image comp)
        {
            long uuid;
            int instanceID = comp.GetInstanceID();
            if (s_Binder.TryGetValue(instanceID, out uuid))
            {
                Res.Stop(uuid);
                s_Binder.Remove(instanceID);
            }

            Res.UnSpawn(comp.sprite);
            comp.sprite = null;
        }
    }
}

